package com.rwy.util;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.propertyeditors.LocaleEditor;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.WebUtils;


public class WebUtil extends WebUtils{

	public final static String AJAX_HEADER = "x-requested-with";
	public final static String XMLHTTPREQUEST = "XMLHttpRequest";
	public final static String LOG_OBJECT = "log_object";
	
/*	@Autowired
	@Qualifier("propertyConfigurer")
	private static CustomPropertyPlaceholderConfigurer propertyConfigurer;
	*/
	public static boolean isAjaxRequest() {
		return isAjaxRequest(getHttpServletRequest());
	}
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestType = request.getHeader(AJAX_HEADER);
		return XMLHTTPREQUEST.equalsIgnoreCase(requestType);
	}
	
	public static String getRemoteAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public static Map<String, String> getParameters(HttpServletRequest request) {
		
		Map<String, String> map = new HashMap<String, String>();  
		
	    Enumeration<String> paramNames = request.getParameterNames();  
	    
		while (paramNames.hasMoreElements()) {  
	    	String paramName = (String) paramNames.nextElement();  
	    	String[] paramValues = request.getParameterValues(paramName);  
	    	
	    	if (paramValues.length == 1) {  
	    		String paramValue = paramValues[0];  
			    if (paramValue.length() != 0) {
			        map.put(paramName, paramValue);  
			    }  
			}  
	    }
		return map;
	}
	
	
	
	public static void setLocale(HttpServletRequest request, LangEnum lang) {
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		String l = "";
		
		switch(lang) {
		case CN:
			l = "zh";
			break;
		case EN:
			l = "en";
			break;
		default:
			l = "en";
		}
		
		LocaleEditor localeEditor = new LocaleEditor();  
		localeEditor.setAsText(l);  
		localeResolver.setLocale(request, ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse(), (Locale) localeEditor.getValue()); 
	}
	
	public enum LangEnum {
			CN,
			EN
	}
	 
	/*public static void updateServerRequestLastingTime(ServerRequest request) {
		request.setLastingTime(new Date().getTime() - request.getVisitTime().getTime());
	}*/

	public static HttpSession getHttpSession() {
		return getHttpServletRequest().getSession();
	}
	
	public static HttpSession getHttpSession(HttpServletRequest request) {
		return request.getSession();
	}
	
	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	public static String[] getParameterValues(String parameterName) {
		return getHttpServletRequest().getParameterValues(parameterName);
	}
	
	public static String getParameterValue(String parameterName) {
		return getHttpServletRequest().getParameter(parameterName);
	}
	
	public static void setAttribute(String attributeName, Object obj) {
		getHttpServletRequest().setAttribute(attributeName, obj);
	}
	
	public static Object getAttribute(String attributeName) {
		return getHttpServletRequest().getAttribute(attributeName);
	}
	
	public static void setAttribute(HttpServletRequest request, String attributeName, Object obj) {
		request.setAttribute(attributeName, obj);
	}
	
	public static Object getAttribute(HttpServletRequest request, String attributeName) {
		return request.getAttribute(attributeName);
	}
	
	public static Object getObjectInSession(String key) {
		return getHttpSession().getAttribute(key);
	}
	
	public static Object getObjectInSession(HttpServletRequest request, String key) {
		return getHttpSession(request).getAttribute(key);
	}
	
	public static void jsonWrite(Object model, HttpServletResponse response) {
		jsonWrite(model, null, response);
	}
	
	public static void jsonWrite(Object model, MediaType contentType, HttpServletResponse response) {
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
		try {
			converter.write(model, contentType, outputMessage);
		} catch (HttpMessageNotWritableException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	
	
	/**
	 * @Title: createCookieToResponse
	 * @Description: 创建Cookie
	 * @param string
	 * @param token
	 * @param i
	 * @param string2
	 */
	public static Cookie createCookieToResponse(String name, String value, Integer maxAge, String path) {
		Cookie c = new Cookie(name, value);
		if (ObjectUtil.isNullForInt(maxAge)) {
			c.setMaxAge(30*24*3600);
		} else {
			c.setMaxAge(maxAge);			
		}
		if (StringUtil.isEmpty(path)) {
			c.setPath("/");
		} else {
			c.setPath(path);
		}
		return c;
	}
}
